package com.demo.maintenance.adapter;

import android.text.TextUtils;
import android.util.Log;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.fastjson.JSON;
import com.demo.maintenance.bean.FileResponse;
import com.demo.maintenance.contant.Global;
import com.demo.maintenance.utils.HttpManager;
import com.hjq.toast.ToastUtils;
import com.kongzue.dialogx.dialogs.WaitDialog;

public abstract class BaseUploadAdapter<T extends RecyclerView.ViewHolder> extends DelegateAdapter.Adapter<T> {

    public void uploadFile(String filePath, UploadSuccessListener listener){
        WaitDialog.show("Uploading");

        String url = Global.ipAddress + "servlet/UploadImages";

        try {
            HttpManager.postFile(url, filePath, new HttpManager.NetworkCallBack() {
                @Override
                public void onSuccess(String successInfo) {
                    try{
                        // 去除首尾花括号
                        int lastIndex = successInfo.lastIndexOf("\"");
                        successInfo = successInfo.substring(1, lastIndex);
                        successInfo = successInfo.replace("\\", "");

                        FileResponse fileResponse = JSON.parseObject(successInfo, FileResponse.class);
                        listener.onSuccess(Global.ipAddress + "/upload/" + fileResponse.data.src);

                        Log.e("monitoring", "上传图片成功，路径：" + Global.ipAddress + "upload/" + fileResponse.data.src);

                    }catch (Exception e){
                        e.printStackTrace();
                        ToastUtils.show("上传文件失败！01");
                    }
//
                }

                @Override
                public void onError(String errorInfo) {
                    Log.e("monitoring", TextUtils.isEmpty(errorInfo) ? "nothing" : errorInfo);
                    ToastUtils.show("上传文件失败！02");
                }

                @Override
                public void onFinal() {
                    WaitDialog.dismiss();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            WaitDialog.dismiss();
            ToastUtils.show("上传文件失败！03");
        }
    }

    public interface UploadSuccessListener {

        void onSuccess(String fileUrl);

    }

}
